package server;

import pojo.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class register {
    /**
                     * 键t盘输账号和密码
                     * 提示登录是否成功
     *      接受用户名和密码
     *      根据用户名和密码查数据库
     *      查到用户提示登录成功
     *      查不到提示用户名或密码错误
     */
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = scanner.nextLine();
        System.out.println("请输入密  码");
        String password = scanner.nextLine();
        User user = find(username, password);
        if (user != null){
            System.out.println("欢迎登录" + user.getName());
        }else{
            System.out.println("账户或密码错误");
        }


    }
    public static User find(String username,String password) throws Exception {
        Connection conn = getConnection();
        Statement statement = conn.createStatement();
        //登录数据库的sql语句
        String sql = "select * from user where username='"+username+"'and password='"+password+"'";
        User user = null;
        ResultSet resultSet = statement.executeQuery(sql);
        if (resultSet.next()){
            user = new User();
            user.setId(resultSet.getInt("id"));
            user.setName(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            user.setSex(resultSet.getString("sex"));
            user.setBithday(resultSet.getString("bithday"));
        }

        resultSet.close();
        statement.close();
        conn.close();

        return user;
    }

    //工具类 获取数据库的连接
    public static Connection getConnection(){
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mybattis?serverTimezone=UTC";
            String username = "root";
            String password ="root";
            conn = DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}
